package org.uned.agonzalo16.bitacora.web.user;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.User;

@Service
public class UserValidator {

	@Autowired
	private UserDao userDao;

	public void validate(UserForm form, Errors errors) {
		if (errors.hasErrors()) {
			return;
		}

		List<User> users = userDao.findAll();

		for (User user : users) {
			// si el usuario es el mismo, ignorar
			if (form.getId() != null && user.getId() == form.getId()) {
				continue;
			}

			if (user.getEmail().equals(form.getEmail())) {
				errors.rejectValue("email", "duplicate", "duplicate");
			}

			if (user.getUsername().equals(form.getUsername())) {
				errors.rejectValue("username", "duplicate", "duplicate");
			}
		}

		if (form.getId() == null && StringUtils.isEmpty(form.getPassword())) {
			errors.rejectValue("password", "empty", "empty");
		}
	}
}
